#pragma once

#include <AVUIUIElement.h>
#include <AVUIFrameworkPropertyMetadata.h>
#include <AVUILength.h>
#include <AVUIBinding.h>
#include <AVUIToolTipService.h>
#include <AVUIRoutedEventHandlerInfo.h>
#include <AVUILoadInitialize.h>
#include <AVUIIHaveResources.h>

namespace AVUI {

class Storyboard;
class BindingExpression;
class TraversalRequest;
class InputScope;
class XmlLanguage;
class ContextMenuEventHandler;
class ContextMenuEventArgs;
class RequestBringIntoViewEventHandler;
class DependencyPropertyChangedEventHandler;
class SizeChangedEventHandler;
class DataTransferEventHandler;
class FrameworkContentElement;
struct ChildRecord;
struct TreeChangeInfo;
class AncestorChangedEventArgs;
struct InheritablePropertyChangeInfo;
class KeyboardNavigation;
class InheritedPropertyChangedEventHandler;
class PropertyInfo;
class NumberSubstitution;
class FrameworkServices;
class XmlNamespaceManager;
class InheritedPropertyChangedEventArgs;
class Visual3D;
class DataTemplate;
typedef ItemStructList< DependencyProperty* > DependencyPropertyList;
class Style;

class InternalFlags
{
public:
    enum Enum
    {
        AncestorChangeInProgress = 0x80000,
        CreatingRoot = 0x10000000,
        HasHeightEverChanged = 0x1000,
        HasImplicitStyleFromResources = 4,
        HasLocalStyle = 0x800000,
        HasLogicalChildren = 0x4000000,
        HasNumberSubstitutionChanged = 2,
        HasResourceReferences = 1,
        HasStyleEverBeenFetched = 0x200000,
        HasTemplateGeneratedSubTree = 0x1000000,
        HasThemeStyleEverBeenFetched = 0x400000,
        HasWidthEverChanged = 0x800,
        InheritanceBehavior0 = 8,
        InheritanceBehavior1 = 0x10,
        InheritanceBehavior2 = 0x20,
        InitPending = 0x10000,
        InVisibilityCollapsedTree = 0x100000,
        IsInitialized = 0x8000,
        IsLogicalChildrenIterationInProgress = 0x8000000,
        IsResourceParentValid = 0x20000,
        IsRightToLeft = 0x20000000,
        IsStyleUpdateInProgress = 0x40,
        IsThemeStyleUpdateInProgress = 0x80,
        NeedsClipBounds = 0x400,
        PotentiallyHasMentees = 0x80000000,
        ShouldLookupImplicitStyles = 0x40000000,
        StoresParentTemplateValues = 0x100
    };
};

class InternalFlags2
{
public:
    enum Enum
    {
        BypassLayoutPolicies = 0x80000000,
        Default = 0xffff,
        HasMultipleInheritanceContexts = 0x20000000,
        HasStyleChanged = 0x2000000,
        HasStyleInvalidated = 0x8000000,
        HasTemplateChanged = 0x4000000,
        IsLoadedCache = 0x200000,
        IsParentAnFE = 0x800000,
        IsRequestingExpression = 0x10000000,
        IsStyleSetFromGenerator = 0x400000,
        IsTemplatedParentAnFE = 0x1000000,
        R0 = 1,
        R1 = 2,
        R2 = 4,
        R3 = 8,
        R4 = 0x10,
        R5 = 0x20,
        R6 = 0x40,
        R7 = 0x80,
        R8 = 0x100,
        R9 = 0x200,
        RA = 0x400,
        RB = 0x800,
        RC = 0x1000,
        RD = 0x2000,
        RE = 0x4000,
        RF = 0x8000,
        TreeHasLoadedChangeHandler = 0x100000
    };
};
 
/// <summary>
/// Provides a WPF framework-level set of properties, events, and methods for Windows Presentation Foundation (WPF) elements. 
/// This class represents the provided WPF framework-level implementation built on the WPF core-level APIs defined by <see cref="T:System.Windows.UIElement" />.
/// </summary>
class FrameworkElement : public UIElement, public ILoadInitialize, public IFrameworkInputElement, public IHaveResources
{
    friend class Application;
    friend class ScrollContentPresenter;
    friend class FrameworkObject;
    friend class UIElementCollection;
    friend class InnerItemCollectionView;
    friend class RowDefinitionCollection;
    friend class ColumnDefinitionCollection;
    friend class StyleHelper;
    friend class TreeWalkHelper;
    friend class LogicalTreeHelper;
    friend class UIElementHelper;
    template<class T>
        friend class DescendentsWalker;
public:
    DECLARE_ELEMENT(FrameworkElement, UIElement);

#pragma region Public Methods

    /// <summary>Initializes a new instance of the <see cref="T:System.Windows.FrameworkElement" /> class. </summary>
    FrameworkElement();

    /// <summary>Builds the current template's visual tree if necessary, and returns a value that indicates whether the visual tree was rebuilt by this call. </summary>
    /// <returns>true if visuals were added to the tree; returns false otherwise.</returns>
    bool ApplyTemplate();

    /// <summary>Starts the initialization process for this element. </summary>
    /// <returns />
    virtual void BeginInit();

    /// <summary>Begins the sequence of actions that are contained in the provided storyboard. </summary>
    /// <param name="storyboard">The storyboard to begin.</param>
    void BeginStoryboard(Storyboard* pStoryboard) { BeginStoryboard(pStoryboard, HandoffBehavior::SnapshotAndReplace, false); }

    /// <summary>Begins the sequence of actions contained in the provided storyboard, with options specified for what should happen if the property is already animated. </summary>
    /// <param name="storyboard">The storyboard to begin.</param>
    /// <param name="handoffBehavior">A value of the enumeration that describes behavior to use if a property described in the storyboard is already animated.</param>
    void BeginStoryboard(Storyboard* pStoryboard, HandoffBehavior::Enum handoffBehavior) { BeginStoryboard(pStoryboard, handoffBehavior, false); }

    /// <summary> Begins the sequence of actions contained in the provided storyboard, with specified state for control of the animation after it is started. </summary>
    /// <param name="storyboard">The storyboard to begin. </param>
    /// <param name="handoffBehavior">A value of the enumeration that describes behavior to use if a property described in the storyboard is already animated.</param>
    /// <param name="isControllable">Declares whether the animation is controllable (can be paused) after it is started.</param>
    void BeginStoryboard(Storyboard* pStoryboard, HandoffBehavior::Enum handoffBehavior, bool isControllable);

    /// <summary>Attempts to bring this element into view, within any scrollable regions it is contained within. </summary>
    /// <returns />
    void BringIntoView() { BringIntoView(Rect::get_Empty()); }

    /// <summary>Attempts to bring the provided region size of this element into view, within any scrollable regions it is contained within. </summary>
    /// <returns />
    /// <param name="targetRectangle">Specified size of the element that should also be brought into view. </param>
    void BringIntoView(const Rect& targetRectangle);

    /// <summary>Indicates that the initialization process for the element is complete. </summary>
    /// <exception cref="T:System.InvalidOperationException">
    /// <see cref="M:System.Windows.FrameworkElement.EndInit" /> was called without <see cref="M:System.Windows.FrameworkElement.BeginInit" /> having previously been called on the element.</exception>
    virtual void EndInit();

    /// <summary>Finds an element that has the provided identifier name. </summary>
    /// <returns>The requested element. This can be null if no matching element was found.</returns>
    /// <param name="name">The name of the requested element.</param>
    Object* FindName(String* pName) { DependencyObject* pScopeOwner; return FindName(pName, &pScopeOwner); }

    /// <summary>Searches for a resource with the specified key, and throws an exception if the requested resource is not found. </summary>
    /// <returns>The requested resource. If no resource with the provided key was found, an exception is thrown. An <see cref="F:System.Windows.DependencyProperty.UnsetValue" /> value might also be returned in the exception case.</returns>
    /// <param name="resourceKey">The key identifier for the requested resource.</param>
    /// <exception cref="T:System.Windows.ResourceReferenceKeyNotFoundException">The requested resource key was not found.</exception>
    /// <exception cref="T:System.ArgumentNullException">
    /// <paramref name="resourceKey" /> is null.</exception>
    Object* FindResource(Object* pResourceKey);

    /// <summary>Returns the <see cref="T:System.Windows.Data.BindingExpression" /> that represents the binding on the specified property. </summary>
    /// <returns>A <see cref="T:System.Windows.Data.BindingExpression" /> if the target property has an active binding; otherwise, returns null.</returns>
    /// <param name="pDP">The target <see cref="T:System.Windows.DependencyProperty" /> to get the binding from.</param>
    BindingExpression* GetBindingExpression(DependencyProperty* pDP);

    /// <summary>Moves the keyboard focus away from this element and to another element in a provided traversal direction. </summary>
    /// <returns>Returns true if focus is moved successfully; false if the target element in direction as specified does not exist or could not be keyboard focused.</returns>
    /// <param name="request">The direction that focus is to be moved, as a value of the enumeration.</param>
    virtual bool MoveFocus(TraversalRequest* pRequest) AVUI_OVERRIDE;

    /// <summary>When overridden in a derived class, is invoked whenever application code or internal processes call <see cref="M:System.Windows.FrameworkElement.ApplyTemplate" />.</summary>
    virtual void OnApplyTemplate() { };

    /// <summary>Determines the next element that would receive focus relative to this element for a provided focus movement direction, but does not actually move the focus.</summary>
    /// <returns>The next element that focus would move to if focus were actually traversed. May return null if focus cannot be moved relative to this element for the provided direction.</returns>
    /// <param name="direction">The direction for which a prospective focus change should be determined.</param>
    /// <exception cref="T:System.ComponentModel.InvalidEnumArgumentException">Specified one of the following directions in the <see cref="T:System.Windows.Input.TraversalRequest" />: <see cref="F:System.Windows.Input.FocusNavigationDirection.Next" />, <see cref="F:System.Windows.Input.FocusNavigationDirection.Previous" />, <see cref="F:System.Windows.Input.FocusNavigationDirection.First" />, <see cref="F:System.Windows.Input.FocusNavigationDirection.Last" />. These directions are not legal for <see cref="M:System.Windows.FrameworkElement.PredictFocus(System.Windows.Input.FocusNavigationDirection)" /> (but they are legal for <see cref="M:System.Windows.FrameworkElement.MoveFocus(System.Windows.Input.TraversalRequest)" />). </exception>
    virtual DependencyObject* PredictFocus(FocusNavigationDirection::Enum direction) AVUI_OVERRIDE;

    /// <summary>Provides an accessor that simplifies access to the <see cref="T:System.Windows.NameScope" /> registration method.</summary>
    /// <param name="name">Name to use for the specified name-object mapping.</param>
    /// <param name="scopedElement">Object for the mapping.</param>
    void RegisterName(String* pName, Object* pScopedElement);

    /// <summary>Attaches a binding to this element, based on the provided source property name as a path qualification to the data source. </summary>
    /// <returns>Records the conditions of the binding. This return value can be useful for error checking.</returns>
    /// <param name="pDP">Identifies the destination property where the binding should be established.</param>
    /// <param name="pPath">The source property name or the path to the property used for the binding.</param>
    BindingExpression* SetBinding(DependencyProperty* pDP, String* pPath);

    /// <summary>Attaches a binding to this element, based on the provided binding object. </summary>
    /// <returns>Records the conditions of the binding. This return value can be useful for error checking.</returns>
    /// <param name="pDP">Identifies the property where the binding should be established.</param>
    /// <param name="pBinding">Represents the specifics of the data binding.</param>
    BindingExpressionBase* SetBinding(DependencyProperty* pDP, BindingBase* pBinding);

    /// <summary>Searches for a resource with the specified name and sets up a resource reference to it for the specified property. </summary>
    /// <param name="pDP">The property to which the resource is bound.</param>
    /// <param name="pName">The name of the resource.</param>
    void SetResourceReference(DependencyProperty* pDP, Object* pName);

    /// <summary>Returns whether serialization processes should serialize the contents of the <see cref="P:System.Windows.FrameworkElement.Resources" /> property. </summary>
    /// <returns>true if the <see cref="P:System.Windows.FrameworkElement.Resources" /> property value should be serialized; otherwise, false.</returns>
    bool ShouldSerializeResources();

    /// <summary>Returns whether serialization processes should serialize the contents of the <see cref="P:System.Windows.FrameworkElement.Style" /> property.</summary>
    /// <returns>true if the <see cref="P:System.Windows.FrameworkElement.Style" /> property value should be serialized; otherwise, false.</returns>
    bool ShouldSerializeStyle();

    /// <summary>Returns whether serialization processes should serialize the contents of the <see cref="P:System.Windows.FrameworkElement.Triggers" /> property.</summary>
    /// <returns>true if the <see cref="P:System.Windows.FrameworkElement.Triggers" /> property value should be serialized; otherwise, false.</returns>
    bool ShouldSerializeTriggers();

    /// <summary>Searches for a resource with the specified key, and returns that resource if found. </summary>
    /// <returns>The found resource, or null if no resource with the provided <paramref name="key" /> is found.</returns>
    /// <param name="resourceKey">The key identifier of the resource to be found.</param>
    Object* TryFindResource(Object* pResourceKey);

    /// <summary>Simplifies access to the <see cref="T:System.Windows.NameScope" /> de-registration method.</summary>
    /// <param name="name">Name of the name-object pair to remove from the current scope.</param>
    void UnregisterName(String* pName);

#pragma endregion Public methods
 
#pragma region Public Properties

    /// <summary>Gets the rendered height of this element.  This is a dependency property.</summary>
    /// <returns>The element's height, as a value in device-independent units (1/96th inch per unit). The default value is 0 (zero).</returns>
    float get_ActualHeight() { return get_RenderSize().get_Height(); }
    DECLARE_READONLY_DEPENDENCY_PROPERTY(ActualHeight);

    /// <summary>Gets the rendered height of this element.  This is a dependency property.</summary>
    /// <returns>The element's height, as a value in device-independent units (1/96th inch per unit). The default value is 0 (zero).</returns>
    float get_ActualWidth() { return get_RenderSize().get_Width(); }
    DECLARE_READONLY_DEPENDENCY_PROPERTY(ActualWidth);
 
    /// <summary> Gets or sets the context menu element that should appear whenever the context menu is requested through user interface (UI) from within this element.  This is a dependency property.</summary>
    /// <returns>The context menu assigned to this element. </returns>
    TRefCountedPtr<ContextMenu> get_ContextMenu() { return (ContextMenu*)(Object*)GetValue(get_ContextMenuProperty()); }
    void set_ContextMenu(ContextMenu* pValue) { SetValue(get_ContextMenuProperty(), (Object*)pValue); } 
    DECLARE_DEPENDENCY_PROPERTY(ContextMenu);

    /// <summary> Gets or sets the cursor that displays when the mouse pointer is over this element.  This is a dependency property.</summary>
    /// <returns>The cursor to display. The default value is defined as null per this dependency property. However, the practical default at run time will come from a variety of factors.</returns>
    TRefCountedPtr<Cursor> get_Cursor() { return (Cursor*)(Object*)GetValue(get_CursorProperty()); }
    void set_Cursor(Cursor* pValue) { SetValue(get_CursorProperty(), (Object*)pValue); } 
    DECLARE_DEPENDENCY_PROPERTY(Cursor);

    /// <summary> Gets or sets the data context for an element when it participates in data binding.  This is a dependency property.</summary>
    /// <returns>The object to use as data context.</returns>
    TRefCountedPtr<Object> get_DataContext() { return (Object*)(Object*)GetValue(get_DataContextProperty()); }
    void set_DataContext(Object* pValue) { SetValue(get_DataContextProperty(), (Object*)pValue); } 
    DECLARE_DEPENDENCY_PROPERTY(DataContext);


    /// <summary>Gets the value of the <see cref="P:System.Windows.FrameworkElement.FlowDirection" /> attached property for the specified <see cref="T:System.Windows.DependencyObject" />. </summary>
    /// <returns>The requested flow direction, as a value of the enumeration.</returns>
    /// <param name="element">The element to return a <see cref="P:System.Windows.FrameworkElement.FlowDirection" /> for.</param>
    static FlowDirection::Enum GetFlowDirection(DependencyObject* pElement)
    {
        if (pElement == NULL)
        {
            LibraryThrowException(object_allocate<ArgumentNullException>("pElement"));
        }
        return (FlowDirection::Enum) UnboxValue<int>(pElement->GetValue(get_FlowDirectionProperty()));
    }

    /// <summary>Sets the value of the <see cref="P:System.Windows.FrameworkElement.FlowDirection" /> attached property for the provided element. </summary>
    /// <param name="element">The element that specifies a flow direction.</param>
    /// <param name="value">A value of the enumeration, specifying the direction.</param>
    static void SetFlowDirection(DependencyObject* pElement, FlowDirection::Enum value)
    {
        if (pElement == NULL)
        {
            LibraryThrowException(object_allocate<ArgumentNullException>("pElement"));
        }
        pElement->SetValue(get_FlowDirectionProperty(), BoxValue<int>(value));
    }

    /// <summary>Gets or sets the direction that text and other user interface (UI) elements flow within any parent element that controls their layout.  This is a dependency property.</summary>
    /// <returns>The direction that text and other UI elements flow within their parent element, as a value of the enumeration. The default value is <see cref="F:System.Windows.FlowDirection.LeftToRight" />.</returns>
    FlowDirection::Enum get_FlowDirection() { if(!get_IsRightToLeft()) return FlowDirection::LeftToRight; return FlowDirection::RightToLeft; }
    void set_FlowDirection(FlowDirection::Enum value) { SetValue(get_FlowDirectionProperty(), AVUI::BoxValue<int>(value)); } 
    DECLARE_DEPENDENCY_PROPERTY(FlowDirection);

    /// <summary>Gets or sets a property that enables customization of appearance, effects, or other style characteristics that will apply to this element when it captures keyboard focus.  This is a dependency property.</summary>
    /// <returns>The desired style to apply on focus. The default value as declared in the dependency property is an empty static <see cref="T:System.Windows.Style" />. However, the effective value at run time is often (but not always) a style as supplied by theme support for controls. </returns>
    TRefCountedPtr<Style> get_FocusVisualStyle() { return (Style*)(Object*)GetValue(get_FocusVisualStyleProperty()); }
    void set_FocusVisualStyle(Style* pValue) { SetValue(get_FocusVisualStyleProperty(), (Object*)pValue); } 
    DECLARE_DEPENDENCY_PROPERTY(FocusVisualStyle);

    /// <summary>Gets or sets a value that indicates whether this <see cref="T:System.Windows.FrameworkElement" /> should force the user interface (UI) to render the cursor as declared by the <see cref="P:System.Windows.FrameworkElement.Cursor" /> property.  This is a dependency property.</summary>
    /// <returns>true if cursor presentation while over this element is forced to use current <see cref="P:System.Windows.FrameworkElement.Cursor" /> settings for the cursor (including on all child elements); otherwise false. The default value is false.</returns>
    bool get_ForceCursor() { return AVUI::UnboxValue<bool>(GetValue(get_ForceCursorProperty())); }
    void set_ForceCursor(bool value) { SetValue(get_ForceCursorProperty(), BooleanBoxes::Box(value)); } 
    DECLARE_DEPENDENCY_PROPERTY(ForceCursor);

    /// <summary> Gets or sets the suggested height of the element.  This is a dependency property.</summary>
    /// <returns>The height of the element, in device-independent units (1/96th inch per unit). The default value is <see cref="F:System.Double.NaN" />. This value must be equal to or greater than 0.0. See Remarks for upper bound information.</returns>
    float get_Height() { return AVUI::UnboxValue<float>(GetValue(get_HeightProperty())); }
    void set_Height(float value) { SetValue(get_HeightProperty(), AVUI::BoxValue(value)); } 
    DECLARE_DEPENDENCY_PROPERTY_BEGIN(Height);
        DECLARE_ATTRIBUTE_CONVERTER(LengthTypeConverter)
    DECLARE_DEPENDENCY_PROPERTY_END();

    /// <summary>Gets or sets the horizontal alignment characteristics applied to this element when it is composed within a parent element, such as a panel or items control.  This is a dependency property.</summary>
    /// <returns>A horizontal alignment setting, as a value of the enumeration. The default is <see cref="F:System.Windows.HorizontalAlignment.Stretch" />.</returns>
    HorizontalAlignment::Enum get_HorizontalAlignment() { return (HorizontalAlignment::Enum)(AVUI::UnboxValue<int>(GetValue(get_HorizontalAlignmentProperty()))); }
    void set_HorizontalAlignment(HorizontalAlignment::Enum value) { SetValue(get_HorizontalAlignmentProperty(), AVUI::BoxValue<int>(value)); } 
    DECLARE_DEPENDENCY_PROPERTY(HorizontalAlignment);

    /// <summary>Gets or sets the context for input used by this <see cref="T:System.Windows.FrameworkElement" />.  This is a dependency property.</summary>
    /// <returns>The input scope, which modifies how input from alternative input methods is interpreted. The default value is null (which results in a default handling of commands).</returns>
    TRefCountedPtr<InputScope> get_InputScope() { return (InputScope*)(Object*)GetValue(get_InputScopeProperty()); }
    void set_InputScope(InputScope* pValue) { SetValue(get_InputScopeProperty(), (Object*)pValue); } 
    DECLARE_DEPENDENCY_PROPERTY(InputScope);

    /// <summary>Gets a value that indicates whether this element has been initialized, either during processing by a XAML processor, or by explicitly having its <see cref="M:System.Windows.FrameworkElement.EndInit" /> method called. </summary>
    /// <returns>true if the element is initialized per the aforementioned XAML processing or method calls; otherwise, false.</returns>
    bool get_IsInitialized() { return ReadInternalFlag(InternalFlags::IsInitialized); }
    DECLARE_READONLY_PROPERTY(IsInitialized, bool, false);

    /// <summary>Gets a value that indicates whether this element has been loaded for presentation. </summary>
    /// <returns>true if the current element is attached to an element tree; false if the element has never been attached to a loaded element tree. </returns>
    bool get_IsLoaded();
    DECLARE_READONLY_PROPERTY(IsLoaded, bool, false);

    /// <summary>Gets or sets localization/globalization language information that applies to an  element. This is a dependency property.</summary>
    /// <returns>The language information for this element. The default value is an <see cref="T:System.Windows.Markup.XmlLanguage" /> with its <see cref="P:System.Windows.Markup.XmlLanguage.IetfLanguageTag" /> value set to the string "en-US".</returns>
    TRefCountedPtr<XmlLanguage> get_Language() { return (XmlLanguage*)(Object*)GetValue(get_LanguageProperty()); }
    void set_Language(XmlLanguage* pValue) { SetValue(get_LanguageProperty(), (Object*)pValue); } 
    DECLARE_DEPENDENCY_PROPERTY(Language);
 
    /// <summary> Gets or sets a graphics transformation that should apply to this element when  layout is performed. This is a dependency property.</summary>
    /// <returns>The transform this element should use. The default is <see cref="P:System.Windows.Media.Transform.Identity" />.</returns>
    TRefCountedPtr<Transform> get_LayoutTransform() { return (Transform*)(Object*)GetValue(get_LayoutTransformProperty()); }
    void set_LayoutTransform(Transform* pValue) { SetValue(get_LayoutTransformProperty(), (Object*)pValue); } 
    DECLARE_DEPENDENCY_PROPERTY(LayoutTransform);

    /// <summary>Gets or sets the outer margin of an element.  This is a dependency property.</summary>
    /// <returns>Provides margin values for the element. The default value is a <see cref="T:System.Windows.Thickness" /> with all properties equal to 0 (zero).</returns>
    Thickness get_Margin() { return AVUI::UnboxValue<Thickness>(GetValue(get_MarginProperty())); }
    void set_Margin(const Thickness& value) { SetValue(get_MarginProperty(), AVUI::BoxValue(value)); } 
    DECLARE_DEPENDENCY_PROPERTY(Margin);

    /// <summary>Gets or sets the maximum height constraint of the element.  This is a dependency property.</summary>
    /// <returns>The maximum height of the element, in device-independent units (1/96th inch per unit). The default value is <see cref="F:System.Double.PositiveInfinity" />. This value can be any value equal to or greater than 0.0. <see cref="F:System.Double.PositiveInfinity" /> is also valid.</returns>
    float get_MaxHeight() { return AVUI::UnboxValue<float>(GetValue(get_MaxHeightProperty())); }
    void set_MaxHeight(float value) { SetValue(get_MaxHeightProperty(), AVUI::BoxValue(value)); } 
    DECLARE_DEPENDENCY_PROPERTY_BEGIN(MaxHeight);
        DECLARE_ATTRIBUTE_CONVERTER(LengthTypeConverter)
    DECLARE_DEPENDENCY_PROPERTY_END();

    /// <summary>Gets or sets the maximum height constraint of the element.  This is a dependency property.</summary>
    /// <returns>The maximum height of the element, in device-independent units (1/96th inch per unit). The default value is <see cref="F:System.Double.PositiveInfinity" />. This value can be any value equal to or greater than 0.0. <see cref="F:System.Double.PositiveInfinity" /> is also valid.</returns>
    float get_MaxWidth() { return AVUI::UnboxValue<float>(GetValue(get_MaxWidthProperty())); }
    void set_MaxWidth(float value) { SetValue(get_MaxWidthProperty(), AVUI::BoxValue(value)); } 
    DECLARE_DEPENDENCY_PROPERTY_BEGIN(MaxWidth);
        DECLARE_ATTRIBUTE_CONVERTER(LengthTypeConverter)
    DECLARE_DEPENDENCY_PROPERTY_END();

    /// <summary>Gets or sets the minimum height constraint of the element.  This is a dependency property.</summary>
    /// <returns>The minimum height of the element, in device-independent units (1/96th inch per unit). The default value is 0.0. This value can be any value equal to or greater than 0.0. However, <see cref="F:System.Double.PositiveInfinity" /> is NOT valid, nor is <see cref="F:System.Double.NaN" />.</returns>
    float get_MinHeight() { return AVUI::UnboxValue<float>(GetValue(get_MinHeightProperty())); }
    void set_MinHeight(float value) { SetValue(get_MinHeightProperty(), AVUI::BoxValue(value)); } 
    DECLARE_DEPENDENCY_PROPERTY_BEGIN(MinHeight);
        DECLARE_ATTRIBUTE_CONVERTER(LengthTypeConverter)
    DECLARE_DEPENDENCY_PROPERTY_END();

    /// <summary> Gets or sets the minimum width constraint of the element.  This is a dependency property.</summary>
    /// <returns>The minimum width of the element, in device-independent units (1/96th inch per unit). The default value is 0.0. This value can be any value equal to or greater than 0.0. However, <see cref="F:System.Double.PositiveInfinity" /> is not valid, nor is <see cref="F:System.Double.NaN" />.</returns>
    float get_MinWidth() { return AVUI::UnboxValue<float>(GetValue(get_MinWidthProperty())); }
    void set_MinWidth(float value) { SetValue(get_MinWidthProperty(), AVUI::BoxValue(value)); } 
    DECLARE_DEPENDENCY_PROPERTY_BEGIN(MinWidth);
        DECLARE_ATTRIBUTE_CONVERTER(LengthTypeConverter)
    DECLARE_DEPENDENCY_PROPERTY_END();

    /// <summary>Gets or sets the identifying name of the element. The name provides a reference so that code-behind, such as event handler code, can refer to a markup element after it is constructed during processing by a XAML processor. This is a dependency property.</summary>
    /// <returns>The name of the element. The default is an empty string.</returns>
    TRefCountedPtr<String> get_Name() { return (String*)(Object*)GetValue(get_NameProperty()); }
    void set_Name(String* pValue) { SetValue(get_NameProperty(), (Object*)pValue); } 
    DECLARE_DEPENDENCY_PROPERTY(Name);

    bool get_OverridesDefaultStyle() { return AVUI::UnboxValue<bool>(GetValue(get_OverridesDefaultStyleProperty())); }
    void set_OverridesDefaultStyle(bool value) { SetValue(get_OverridesDefaultStyleProperty(), BooleanBoxes::Box(value)); } 
    DECLARE_DEPENDENCY_PROPERTY(OverridesDefaultStyle);

    /// <summary>Gets the logical parent  element of this element. </summary>
    /// <returns>This element's logical parent.</returns>
    DependencyObject* get_Parent() { return ContextVerifiedGetParent(); }
    DECLARE_READONLY_PROPERTY(Parent, DependencyObject, false);

    /// <summary> Gets or sets the locally-defined resource dictionary. </summary>
    /// <returns>The current locally-defined dictionary of resources, where each resource can be accessed by key.</returns>
    ResourceDictionary* get_Resources();
    void set_Resources(ResourceDictionary* pValue);
    DECLARE_PROPERTY(Resources, ResourceDictionary, false);

    /// <summary>Gets or sets the style used by this element when it is rendered.  This is a dependency property.</summary>
    /// <returns>The applied, nondefault style for the element, if present. Otherwise, null. The default for a default-constructed <see cref="T:System.Windows.FrameworkElement" /> is null.</returns>
    TRefCountedPtr<Style> get_Style() { return m_pStyleCache; }
    void set_Style(Style* pValue) { SetValue(get_StyleProperty(), (Object*)pValue); } 
    DECLARE_DEPENDENCY_PROPERTY(Style);

    /// <summary>Gets or sets an arbitrary object value that can be used to store custom information about this element.  This is a dependency property.</summary>
    /// <returns>The intended value. This property has no default value.</returns>
    TRefCountedPtr<Object> get_Tag() { return (Object*)GetValue(get_TagProperty()); }
    void set_Tag(Object* pValue) { SetValue(get_TagProperty(), pValue); } 
    DECLARE_DEPENDENCY_PROPERTY(Tag);

    /// <summary>Gets a reference to the template parent of this element. This property is not relevant if the element was not created through a template.</summary>
    /// <returns>The element whose <see cref="T:System.Windows.FrameworkTemplate" /> <see cref="P:System.Windows.FrameworkTemplate.VisualTree" /> caused this element to be created. This value is frequently null; see Remarks.</returns>
    DependencyObject* get_TemplatedParent() { return m_pTemplatedParent; }
    DECLARE_READONLY_PROPERTY(TemplatedParent, DependencyObject, false);

    TRefCountedPtr<Object> get_ToolTip() { return ToolTipService::GetToolTip(this); }
    void set_ToolTip(Object* pValue) { ToolTipService::SetToolTip(this, pValue); } 
    DECLARE_DEPENDENCY_PROPERTY(ToolTip);

    /// <summary>Gets the collection of triggers established directly on this element, or in child elements. </summary>
    /// <returns>A strongly typed collection of <see cref="T:System.Windows.Trigger" /> objects.</returns>
    TriggerCollection* get_Triggers();
    DECLARE_READONLY_PROPERTY(Triggers, TriggerCollection, false);

    /// <summary>Gets or sets the vertical alignment characteristics applied to this element when it is composed within a parent element such as a panel or items control.  This is a dependency property.</summary>
    /// <returns>A vertical alignment setting. The default is <see cref="F:System.Windows.VerticalAlignment.Stretch" />.</returns>
    VerticalAlignment::Enum get_VerticalAlignment() { return (VerticalAlignment::Enum)(AVUI::UnboxValue<int>(GetValue(get_VerticalAlignmentProperty()))); }
    void set_VerticalAlignment(VerticalAlignment::Enum value) { SetValue(get_VerticalAlignmentProperty(), AVUI::BoxValue<int>(value)); } 
    DECLARE_DEPENDENCY_PROPERTY(VerticalAlignment);

    /// <summary> Gets or sets the width of the element.  This is a dependency property.</summary>
    /// <returns>The width of the element, in device-independent units (1/96th inch per unit). The default value is <see cref="F:System.Double.NaN" />. This value must be equal to or greater than 0.0. See Remarks for upper bound information.</returns>
    float get_Width() { return AVUI::UnboxValue<float>(GetValue(get_WidthProperty())); }
    void set_Width(float value) { SetValue(get_WidthProperty(), AVUI::BoxValue(value)); } 
    DECLARE_DEPENDENCY_PROPERTY_BEGIN(Width);
        DECLARE_ATTRIBUTE_CONVERTER(LengthTypeConverter)
    DECLARE_DEPENDENCY_PROPERTY_END();

#pragma endregion Public Properties
 
#pragma region Public Events

    /// <summary>Occurs just before any context menu on the element is closed. </summary>
    void add_ContextMenuClosing(ContextMenuEventHandler* pValue) { AddHandler(get_ContextMenuClosingEvent(), (Delegate*)pValue); }
    void remove_ContextMenuClosing(ContextMenuEventHandler* pValue) { RemoveHandler(get_ContextMenuClosingEvent(), (Delegate*)pValue); }
    DECLARE_ROUTED_EVENT(ContextMenuClosing);

    /// <summary>Occurs when any context menu on the element is opened. </summary>
    void add_ContextMenuOpening(ContextMenuEventHandler* pValue) { AddHandler(get_ContextMenuOpeningEvent(), (Delegate*)pValue); }
    void remove_ContextMenuOpening(ContextMenuEventHandler* pValue) { RemoveHandler(get_ContextMenuOpeningEvent(), (Delegate*)pValue); }
    DECLARE_ROUTED_EVENT(ContextMenuOpening);

    /// <summary>Occurs when the data context for this element changes. </summary>
    void add_DataContextChanged(DependencyPropertyChangedEventHandler* pValue) { AddEventHandler(get_DataContextChangedEvent(), (Delegate*)pValue); }
    void remove_DataContextChanged(DependencyPropertyChangedEventHandler* pValue) { RemoveEventHandler(get_DataContextChangedEvent(), (Delegate*)pValue); }
    DECLARE_EVENT(DataContextChanged);

    /// <summary>Occurs when this <see cref="T:System.Windows.FrameworkElement" /> is initialized. This event coincides with cases where the value of the <see cref="P:System.Windows.FrameworkElement.IsInitialized" /> property changes from false (or undefined) to true. </summary>
    void add_Initialized(EventHandler* pValue) { AddEventHandler(get_InitializedEvent(), (Delegate*)pValue); }
    void remove_Initialized(EventHandler* pValue) { RemoveEventHandler(get_InitializedEvent(), (Delegate*)pValue); }
    DECLARE_EVENT(Initialized);

    /// <summary>Occurs when the element is laid out, rendered, and ready for interaction. </summary>
    void add_Loaded(RoutedEventHandler* pValue) { AddHandler(get_LoadedEvent(), (Delegate*)pValue, false); }
    void remove_Loaded(RoutedEventHandler* pValue) { RemoveHandler(get_LoadedEvent(), (Delegate*)pValue); }
    DECLARE_ROUTED_EVENT(Loaded);

    /// <summary>Occurs when <see cref="M:System.Windows.FrameworkElement.BringIntoView(System.Windows.Rect)" /> is called on this element. </summary>
    void add_RequestBringIntoView(RequestBringIntoViewEventHandler* pValue) { AddHandler(get_RequestBringIntoViewEvent(), (Delegate*)pValue, false); }
    void remove_RequestBringIntoView(RequestBringIntoViewEventHandler* pValue) { RemoveHandler(get_RequestBringIntoViewEvent(), (Delegate*)pValue); }
    DECLARE_ROUTED_EVENT(RequestBringIntoView);

    /// <summary>Occurs when either the <see cref="P:System.Windows.FrameworkElement.ActualHeight" /> or the <see cref="P:System.Windows.FrameworkElement.ActualWidth" /> properties change value on this element. </summary>
    void add_SizeChanged(SizeChangedEventHandler* pValue) { AddHandler(get_SizeChangedEvent(), (Delegate*)pValue, false); }
    void remove_SizeChanged(SizeChangedEventHandler* pValue) { RemoveHandler(get_SizeChangedEvent(), (Delegate*)pValue); }
    DECLARE_ROUTED_EVENT(SizeChanged);

    /// <summary>Occurs when the source value changes for any existing property binding on this element.</summary>
    void add_SourceUpdated(DataTransferEventHandler* pValue) { AddHandler(Binding::get_SourceUpdatedEvent(), (Delegate*)pValue); }
    void remove_SourceUpdated(DataTransferEventHandler* pValue) { RemoveHandler(Binding::get_SourceUpdatedEvent(), (Delegate*)pValue); }

    /// <summary>Occurs when the target value changes for any property binding on this element. </summary>
    void add_TargetUpdated(DataTransferEventHandler* pValue) { AddHandler(Binding::get_TargetUpdatedEvent(), (Delegate*)pValue); }
    void remove_TargetUpdated(DataTransferEventHandler* pValue) { RemoveHandler(Binding::get_TargetUpdatedEvent(), (Delegate*)pValue); }

    /// <summary>Occurs just before any tooltip on the element is closed. </summary>
    void add_ToolTipClosing(ToolTipEventHandler* pValue) { AddHandler(get_ToolTipClosingEvent(), (Delegate*)pValue, false); }
    void remove_ToolTipClosing(ToolTipEventHandler* pValue) { RemoveHandler(get_ToolTipClosingEvent(), (Delegate*)pValue); }
    DECLARE_ROUTED_EVENT(ToolTipClosing);

    /// <summary>Occurs just before any tooltip on the element is closed. </summary>
    void add_ToolTipOpening(ToolTipEventHandler* pValue) { AddHandler(get_ToolTipOpeningEvent(), (Delegate*)pValue, false); }
    void remove_ToolTipOpening(ToolTipEventHandler* pValue) { RemoveHandler(get_ToolTipOpeningEvent(), (Delegate*)pValue); }
    DECLARE_ROUTED_EVENT(ToolTipOpening);

    /// <summary>Occurs when the element is removed from within an element tree of loaded elements. </summary>
    void add_Unloaded(RoutedEventHandler* pValue) { AddHandler(get_UnloadedEvent(), (Delegate*)pValue, false); }
    void remove_Unloaded(RoutedEventHandler* pValue) { RemoveHandler(get_UnloadedEvent(), (Delegate*)pValue); }
    DECLARE_ROUTED_EVENT(Unloaded);

#pragma endregion Public Events

protected:

#pragma region Protected Methods

    /// <summary>Adds the provided object to the logical tree of this element. </summary>
    /// <returns />
    /// <param name="pChild">Child element to be added.</param>
    void AddLogicalChild(Object* pChild);

    /// <summary>Implements <see cref="M:System.Windows.UIElement.ArrangeCore(System.Windows.Rect)" /> (defined as virtual in <see cref="T:System.Windows.UIElement" />) and seals the implementation.</summary>
    /// <returns />
    /// <param name="finalRect">The final area within the parent that this element should use to arrange itself and its children.</param>
    virtual void ArrangeCore(const Rect& finalRect) AVUI_OVERRIDE;

    /// <summary>When overridden in a derived class, positions child elements and determines a size for a <see cref="T:System.Windows.FrameworkElement" /> derived class. </summary>
    /// <returns>The actual size used.</returns>
    /// <param name="finalSize">The final area within the parent that this element should use to arrange itself and its children.</param>
    virtual Size ArrangeOverride(const Size& finalSize) { return finalSize; }

    /// <summary>Returns a geometry for a clipping mask. The mask applies if the layout system attempts to arrange an element that is larger than the available display space.</summary>
    /// <returns>The clipping geometry.</returns>
    /// <param name="layoutSlotSize">The size of the part of the element that does visual presentation. </param>
    virtual TRefCountedPtr<Geometry> GetLayoutClip(const Size& layoutSlotSize) AVUI_OVERRIDE;

    /// <summary>Do not use. Use <see cref="M:System.Windows.FrameworkTemplate.FindName(System.String,System.Windows.FrameworkElement)" /> instead. </summary>
    /// <returns>The requested element. May be null if no element of the requested name exists.</returns>
    /// <param name="childName">Name of the child to find.</param>
    virtual DependencyObject* GetTemplateChild(String* pChildName);

    /// <summary>Returns an alternative logical parent for this element if there is no visual parent.</summary>
    /// <returns>Returns something other than null whenever a WPF framework-level implementation of this method has a non-visual parent connection.</returns>
    virtual DependencyObject* GetUIParentCore() AVUI_OVERRIDE { return m_pParent; }

    /// <summary>Overrides <see cref="M:System.Windows.Media.Visual.GetVisualChild(System.Int32)" />, and returns a child at the specified index from a collection of child elements. </summary>
    /// <returns>The requested child element. This should not return null; if the provided index is out of range, an exception is thrown.</returns>
    /// <param name="index">The zero-based index of the requested child element in the collection.</param>
    Visual* GetVisualChild(int index) AVUI_OVERRIDE;

    /// <summary>Implements basic measure-pass layout system behavior for <see cref="T:System.Windows.FrameworkElement" />. </summary>
    /// <returns>The desired size of this element in layout.</returns>
    /// <param name="availableSize">The available size that the parent element can give to the child elements.</param>
    Size MeasureCore(const Size& availableSize) AVUI_OVERRIDE;

    /// <summary>When overridden in a derived class, measures the size in layout required for child elements and determines a size for the <see cref="T:System.Windows.FrameworkElement" />-derived class. </summary>
    /// <returns>The size that this element determines it needs during layout, based on its calculations of child element sizes.</returns>
    /// <param name="availableSize">The available size that this element can give to child elements. Infinity can be specified as a value to indicate that the element will size to whatever content is available.</param>
    virtual Size MeasureOverride(const Size& availableSize) { return Size(0.0f, 0.0f); }
 
    /// <summary> Invoked whenever an unhandled <see cref="E:System.Windows.FrameworkElement.ContextMenuClosing" /> routed event reaches this class in its route. Implement this method to add class handling for this event. </summary>
    /// <param name="e">Provides data about the event.</param>
    virtual void OnContextMenuClosing(ContextMenuEventArgs* e) { }

    /// <summary> Invoked whenever an unhandled <see cref="E:System.Windows.FrameworkElement.ContextMenuOpening" /> routed event reaches this class in its route. Implement this method to add class handling for this event. </summary>
    /// <returns />
    /// <param name="e">The <see cref="T:System.Windows.RoutedEventArgs" /> that contains the event data.</param>
    virtual void OnContextMenuOpening(ContextMenuEventArgs* e) { }
 
    /// <summary>Invoked whenever an unhandled <see cref="E:System.Windows.UIElement.GotFocus" /> event reaches this element in its route.</summary>
    /// <param name="e">The <see cref="T:System.Windows.RoutedEventArgs" /> that contains the event data.</param>
    virtual void OnGotFocus(RoutedEventArgs* e) AVUI_OVERRIDE { if(get_IsKeyboardFocused()) BringIntoView(); UIElement::OnGotFocus(e); }
 
    /// <summary>Raises the <see cref="E:System.Windows.FrameworkElement.Initialized" /> event. This method is invoked whenever <see cref="P:System.Windows.FrameworkElement.IsInitialized" /> is set to true internally. </summary>
    /// <returns />
    /// <param name="e">The <see cref="T:System.Windows.RoutedEventArgs" /> that contains the event data.</param>
    virtual void OnInitialized(EventArgs* e);

    /// <summary>Invoked whenever the effective value of any dependency property on this <see cref="T:System.Windows.FrameworkElement" /> has been updated. The specific dependency property that changed is reported in the arguments parameter. Overrides <see cref="M:System.Windows.DependencyObject.OnPropertyChanged(System.Windows.DependencyPropertyChangedEventArgs)" />.</summary>
    /// <param name="e">The event data that describes the property that changed, as well as old and new values.</param>
    virtual void OnPropertyChanged(DependencyPropertyChangedEventArgs* e) AVUI_OVERRIDE;

    /// <summary>Raises the <see cref="E:System.Windows.FrameworkElement.SizeChanged" /> event, using the specified information as part of the eventual event data. </summary>
    /// <param name="pSizeInfo">Details of the old and new size involved in the change.</param>
    virtual void OnRenderSizeChanged(SizeChangedInfo* pSizeInfo) AVUI_OVERRIDE;

    /// <summary>Invoked when the style in use on this element changes, which will invalidate the layout. </summary>
    /// <returns />
    /// <param name="pOldStyle">The old style.</param>
    /// <param name="pNewStyle">The new style.</param>
    virtual void OnStyleChanged(Style* pOldStyle, Style* pNewStyle) { set_HasStyleChanged(true); }

    /// <summary> Invoked whenever an unhandled <see cref="E:System.Windows.FrameworkElement.ToolTipClosing" /> routed event reaches this class in its route. Implement this method to add class handling for this event. </summary>
    /// <returns />
    /// <param name="e">Provides data about the event.</param>
    virtual void OnToolTipClosing(ToolTipEventArgs* e) { }
 
    /// <summary> Invoked whenever the <see cref="E:System.Windows.FrameworkElement.ToolTipOpening" /> routed event reaches this class in its route. Implement this method to add class handling for this event. </summary>
    /// <returns />
    /// <param name="e">Provides data about the event.</param>
    virtual void OnToolTipOpening(ToolTipEventArgs* e) { }
 
    /// <summary>Invoked when the parent of this element in the visual tree is changed. Overrides <see cref="M:System.Windows.UIElement.OnVisualParentChanged(System.Windows.DependencyObject)" />.</summary>
    /// <param name="pOldParent">The old parent element. May be null to indicate that the element did not have a visual parent previously.</param>
    virtual void OnVisualParentChanged(DependencyObject* pOldParent) AVUI_OVERRIDE;

    /// <summary> Supports incremental layout implementations in specialized subclasses of <see cref="T:System.Windows.FrameworkElement" />. <see cref="M:System.Windows.FrameworkElement.ParentLayoutInvalidated(System.Windows.UIElement)" />  is invoked when a child element has invalidated a property that is marked in metadata as affecting the parent's measure or arrange passes during layout. </summary>
    /// <param name="child">The child element reporting the change.</param>
    virtual void ParentLayoutInvalidated(UIElement* pChild) { };

    /// <summary>Removes the provided object from this element's logical tree. <see cref="T:System.Windows.FrameworkElement" /> updates the affected logical tree parent pointers to keep in sync with this deletion.</summary>
    /// <param name="pChild">The element to remove.</param>
    void RemoveLogicalChild(Object* pChild);

#pragma endregion Protected Methods
 
#pragma region Protected Properties

    /// <summary>Gets or sets the key to use to reference the style for this control, when theme styles are used or defined.  This is a dependency property.</summary>
    /// <returns>The style key. To work correctly as part of theme style lookup, this value is expected to be the <see cref="T:System.Type" /> of the control being styled.</returns>
    TRefCountedPtr<Object> get_DefaultStyleKey() { return (Object*)GetValue(get_DefaultStyleKeyProperty()); }
    void set_DefaultStyleKey(Object* pValue) { SetValue(get_DefaultStyleKeyProperty(), pValue); } 
    DECLARE_DEPENDENCY_PROPERTY(DefaultStyleKey);

    /// <summary>Gets or sets the scope limits for property value inheritance and resource key lookup.</summary>
    /// <returns>A value of the enumeration. The default is <see cref="F:System.Windows.InheritanceBehavior.Default" />.</returns>
    InheritanceBehavior::Enum get_InheritanceBehavior();
    void set_InheritanceBehavior(InheritanceBehavior::Enum value);

    /// <summary> Gets an enumerator for logical child elements of this element. </summary>
    /// <returns>An enumerator for logical child elements of this element.</returns>
    virtual TRefCountedPtr<Object> get_LogicalChildren() { return NULL; }
 
    /// <summary>Gets the number of visual child elements within this element.</summary>
    /// <returns>The number of visual child elements for this element.</returns>
    int get_VisualChildrenCount() AVUI_OVERRIDE { if(m_pTemplateChild != NULL) return 1; return 0; }

#pragma endregion Protected Properties

public:

#pragma region Internal Methods

    virtual void AddInheritanceContext(DependencyObject* pContext, DependencyProperty* pProperty) AVUI_OVERRIDE;
    static void AddIntermediateElementsToRoute(DependencyObject* pMergePoint, EventRoute* pRoute, RoutedEventArgs* pArgs, DependencyObject* pModelTreeNode);
    static void AddStyleHandlersToEventRoute(FrameworkElement* pFe, FrameworkContentElement* pFce, EventRoute* pRoute, RoutedEventArgs* pArgs);
    virtual void AddToEventRouteCore(EventRoute* pRoute, RoutedEventArgs* pArgs) AVUI_OVERRIDE;
    virtual void AdjustBranchSource(RoutedEventArgs* pArgs) { }
    TRefCountedPtr<Object> AdjustEventSource(RoutedEventArgs* pArgs);
    static bool ApplyMirrorTransform(FlowDirection::Enum parentFD, FlowDirection::Enum thisFD);
    virtual bool BuildRouteCore(EventRoute* pRoute, RoutedEventArgs* pArgs) { return BuildRouteCoreHelper(pRoute, pArgs, true); }
    bool BuildRouteCoreHelper(EventRoute* pRoute, RoutedEventArgs* pArgs, bool shouldAddIntermediateElementsToRoute);
    void ChangeLogicalParent(DependencyObject* pNewParent);
    void ChangeSubtreeHasLoadedChangedHandler(DependencyObject* pMentor);
    DependencyObject* ContextVerifiedGetParent() { return m_pParent; }
    void EvaluateBaseValueCore(DependencyProperty* pDP, PropertyMetadata* pMetadata, EffectiveValueEntry* pNewEntry) AVUI_OVERRIDE;
    static TRefCountedPtr<Object> FindImplicitStyleResource(FrameworkContentElement* pFce, Object* pResourceKey, Object** ppSource);
    static TRefCountedPtr<Object> FindImplicitStyleResource(FrameworkElement* pFe, Object* pResourceKey, Object** ppSource);
    Object* FindName(String* pName, DependencyObject** ppScopeOwner);
    static FrameworkElement* FindNamedFrameworkElement(FrameworkElement* pStartElement, String* pTargetName);
    static Object* FindResourceInternal(FrameworkElement* pFe, FrameworkContentElement* pFce, Object* pResourceKey);
    static Object* FindResourceInternal(FrameworkElement* pFe, FrameworkContentElement* pFce, DependencyProperty* pDP, Object* pResourceKey, Object* pUnlinkedParent, bool deferReference);
    static Object* FindResourceInternal(FrameworkElement* pFe, FrameworkContentElement* pFce, DependencyProperty* pDP, Object* pResourceKey, Object* pUnlinkedParent, bool deferReference, Object** ppSource);
    static Object* FindResourceInternal(FrameworkElement* pFe, FrameworkContentElement* pFce, DependencyProperty* pDP, Object* pResourceKey, Object* pUnlinkedParent, bool deferReference, DependencyObject* pBoundaryElement, Object** ppSource);
    static Object* FindResourceInternal(FrameworkElement* pFe, FrameworkContentElement* pFce, DependencyProperty* pDP, Object* pResourceKey, Object* pUnlinkedParent, bool allowDeferredResourceReference, bool mustReturnDeferredResourceReference, DependencyObject* pBoundaryElement, bool isImplicitStyleLookup, Object** ppSource);
    static Object* FindResourceInTree(FrameworkElement* pFeStart, FrameworkContentElement* pFceStart, DependencyProperty* pDP, Object* pResourceKey, Object* pUnlinkedParent, bool allowDeferredResourceReference, bool mustReturnDeferredResourceReference, DependencyObject* pBoundaryElement, InheritanceBehavior::Enum* pInheritanceBehavior, Object** ppSource);
    Object* FindResourceOnSelf(Object* pResourceKey, bool allowDeferredResourceReference, bool mustReturnDeferredResourceReference);
    static INameScope* FindScope(DependencyObject* pDO) { DependencyObject* pObj2; return FindScope(pDO, &pObj2); }
    static INameScope* FindScope(DependencyObject* pDO, DependencyObject** ppScopeOwner);
    static Object* FindTemplateResourceInternal(DependencyObject* pTarget, Object* pItem, Type* pTemplateType);
    void FireLoadedOnDescendentsInternal();
    void FireUnloadedOnDescendentsInternal();
    static bool GetContainingFrameworkElement(DependencyObject* pCurrent, FrameworkElement** ppFe, FrameworkContentElement** ppFce);
    TRefCountedPtr<Expression> GetExpressionCore(DependencyProperty* pDP, PropertyMetadata* pMetadata);
    static DependencyObject* GetFrameworkParent(Object* pCurrent);
    static bool GetFrameworkParent(FrameworkContentElement* pCurrent, FrameworkElement** ppFeParent, FrameworkContentElement** ppFceParent);
    static bool GetFrameworkParent(FrameworkElement* pCurrent, FrameworkElement** ppFeParent, FrameworkContentElement** ppFceParent);
    TRefCountedPtr<Geometry> GetLayoutClipInternal();
    virtual String* GetPlainText() { return NULL; }
    void GetRawValue(DependencyProperty* pDP, PropertyMetadata* pMetadata, EffectiveValueEntry* pEntry);
    static void GetTemplatedParentChildRecord(DependencyObject* pTemplatedParent, int childIndex, ChildRecord* pChildRecord, bool* pIsChildRecordValid);
    bool HasNonDefaultValue(DependencyProperty* pDP);
    virtual bool IgnoreModelParentBuildRoute(RoutedEventArgs* pArgs) { return false; }
    static void InternalSetLayoutTransform(UIElement* pElement, Transform* pLayoutTransform);
    TRefCountedPtr< DependencyPropertyList > InvalidateTreeDependentProperties(TreeChangeInfo parentTreeState, bool isSelfInheritanceParent);
    virtual void OnAddHandler(RoutedEvent* pRoutedEvent, Delegate* pHandler) AVUI_OVERRIDE;
    virtual void OnAncestorChanged() { }
    void OnAncestorChangedInternal(TreeChangeInfo parentTreeState);
    virtual void OnInheritanceContextChangedCore(EventArgs* args) AVUI_OVERRIDE;
    void OnLoaded(RoutedEventArgs* pArgs) { RaiseEvent(pArgs); }
    virtual void OnNewParent(DependencyObject* pNewParent);
    virtual void OnPreApplyTemplate() { }
    virtual void OnPresentationSourceChanged(bool attached) AVUI_OVERRIDE;
    virtual void OnRemoveHandler(RoutedEvent* pRoutedEvent, Delegate* pHandler) AVUI_OVERRIDE;
    virtual void OnTemplateChangedInternal(FrameworkTemplate* pOldTemplate, FrameworkTemplate* pNewTemplate) { set_HasTemplateChanged(true); }
    virtual void OnThemeChanged() { }
    static void OnThemeStyleChanged(DependencyObject* pDO, Object* pOldValue, Object* pNewValue);
    void OnUnloaded(RoutedEventArgs* pArgs) { RaiseEvent(pArgs); }
    void OnVisualAncestorChanged(Object* pSender, AncestorChangedEventArgs* e);
    void RaiseClrEvent(Object* pKey, EventArgs* pArgs) { InvokeEventHandler(pKey, this, pArgs); }
    void RaiseInheritedPropertyChangedEvent(InheritablePropertyChangeInfo* pInfo);
    bool ReadInternalFlag(InternalFlags::Enum reqFlag) { return ((m_flags & reqFlag) != 0); }
    bool ReadInternalFlag2(InternalFlags2::Enum reqFlag) { return ((m_flags2 & reqFlag) != 0); }
    virtual void RemoveInheritanceContext(DependencyObject* pContext, DependencyProperty* pProperty) AVUI_OVERRIDE;
    static bool ShouldApplyMirrorTransform(FrameworkElement* pFe);
    virtual bool ShouldProvideInheritanceContext(DependencyObject* pTarget, DependencyProperty* pProperty) AVUI_OVERRIDE;
    void UpdateStyleProperty();
    void UpdateThemeStyleProperty();

    void WriteInternalFlag(InternalFlags::Enum reqFlag, bool set)
    {
        if (set)
        {
            m_flags |= reqFlag;
        }
        else
        {
            m_flags &= ~reqFlag;
        }
    }

    void WriteInternalFlag2(InternalFlags2::Enum reqFlag, bool set)
    {
        if (set)
        {
            m_flags2 |= reqFlag;
        }
        else
        {
            m_flags2 &= ~reqFlag;
        }
    }

#pragma endregion Internal Methods

#pragma region Internal Properties

    bool get_AncestorChangeInProgress() { return ReadInternalFlag(InternalFlags::AncestorChangeInProgress); }
    void set_AncestorChangeInProgress(bool value) { return WriteInternalFlag(InternalFlags::AncestorChangeInProgress, value); }

    bool get_BypassLayoutPolicies() { return ReadInternalFlag2(InternalFlags2::BypassLayoutPolicies); }
    void set_BypassLayoutPolicies(bool value) { return WriteInternalFlag2(InternalFlags2::BypassLayoutPolicies, value); }

    static Style* get_DefaultFocusVisualStyle();

    int get_EffectiveValuesInitialSize() AVUI_OVERRIDE { return 7; }

    bool get_HasFefLoadedChangeHandler();

    bool get_HasImplicitStyleFromResources() { return ReadInternalFlag(InternalFlags::HasImplicitStyleFromResources); }
    void set_HasImplicitStyleFromResources(bool value) { return WriteInternalFlag(InternalFlags::HasImplicitStyleFromResources, value); }

    bool get_HasLocalStyle() { return ReadInternalFlag(InternalFlags::HasLocalStyle); }
    void set_HasLocalStyle(bool value) { return WriteInternalFlag(InternalFlags::HasLocalStyle, value); }

    bool get_HasLogicalChildren() { return ReadInternalFlag(InternalFlags::HasLogicalChildren); }
    void set_HasLogicalChildren(bool value) { return WriteInternalFlag(InternalFlags::HasLogicalChildren, value); }

    virtual bool get_HasMultipleInheritanceContexts() { return ReadInternalFlag2(InternalFlags2::HasMultipleInheritanceContexts); }

    bool get_HasNumberSubstitutionChanged() { return ReadInternalFlag(InternalFlags::HasNumberSubstitutionChanged); }
    void set_HasNumberSubstitutionChanged(bool value) { return WriteInternalFlag(InternalFlags::HasNumberSubstitutionChanged, value); }

    bool get_HasResourceReference() { return ReadInternalFlag(InternalFlags::HasResourceReferences); }
    void set_HasResourceReference(bool value) { return WriteInternalFlag(InternalFlags::HasResourceReferences, value); }

    bool get_HasResources();

    bool get_HasStyleChanged() { return ReadInternalFlag2(InternalFlags2::HasStyleChanged); }
    void set_HasStyleChanged(bool value) { return WriteInternalFlag2(InternalFlags2::HasStyleChanged, value); }

    bool get_HasStyleEverBeenFetched() { return ReadInternalFlag(InternalFlags::HasStyleEverBeenFetched); }
    void set_HasStyleEverBeenFetched(bool value) { return WriteInternalFlag(InternalFlags::HasStyleEverBeenFetched, value); }

    bool get_HasStyleInvalidated() { return ReadInternalFlag2(InternalFlags2::HasStyleInvalidated); }
    void set_HasStyleInvalidated(bool value) { return WriteInternalFlag2(InternalFlags2::HasStyleInvalidated, value); }

    bool get_HasTemplateChanged() { return ReadInternalFlag2(InternalFlags2::HasTemplateChanged); }
    void set_HasTemplateChanged(bool value) { return WriteInternalFlag2(InternalFlags2::HasTemplateChanged, value); }

    bool get_HasTemplateGeneratedSubTree() { return ReadInternalFlag(InternalFlags::HasTemplateGeneratedSubTree); }
    void set_HasTemplateGeneratedSubTree(bool value) { return WriteInternalFlag(InternalFlags::HasTemplateGeneratedSubTree, value); }

    bool get_HasThemeStyleEverBeenFetched() { return ReadInternalFlag(InternalFlags::HasThemeStyleEverBeenFetched); }
    void set_HasThemeStyleEverBeenFetched(bool value) { return WriteInternalFlag(InternalFlags::HasThemeStyleEverBeenFetched, value); }

    TRefCountedPtr< ItemStructList<DependencyProperty*> > get_InheritableProperties() { return m_pInheritableProperties; }
    void set_InheritableProperties(ItemStructList<DependencyProperty*>* pValue) { m_pInheritableProperties = pValue; }

    virtual DependencyObject* get_InheritanceContext();

    bool get_InVisibilityCollapsedTree() { return ReadInternalFlag(InternalFlags::InVisibilityCollapsedTree); }
    void set_InVisibilityCollapsedTree(bool value) { return WriteInternalFlag(InternalFlags::InVisibilityCollapsedTree, value); }

    bool get_IsLoadedCache() { return ReadInternalFlag2(InternalFlags2::IsLoadedCache); }
    void set_IsLoadedCache(bool value) { return WriteInternalFlag2(InternalFlags2::IsLoadedCache, value); }

    bool get_IsLogicalChildrenIterationInProgress() { return ReadInternalFlag(InternalFlags::IsLogicalChildrenIterationInProgress); }
    void set_IsLogicalChildrenIterationInProgress(bool value) { return WriteInternalFlag(InternalFlags::IsLogicalChildrenIterationInProgress, value); }

    bool get_IsParentAnFE() { return ReadInternalFlag2(InternalFlags2::IsParentAnFE); }
    void set_IsParentAnFE(bool value) { return WriteInternalFlag2(InternalFlags2::IsParentAnFE, value); }

    bool get_IsRequestingExpression() { return ReadInternalFlag2(InternalFlags2::IsRequestingExpression); }
    void set_IsRequestingExpression(bool value) { return WriteInternalFlag2(InternalFlags2::IsRequestingExpression, value); }

    bool get_IsRightToLeft() { return ReadInternalFlag(InternalFlags::IsRightToLeft); }
    void set_IsRightToLeft(bool value) { return WriteInternalFlag(InternalFlags::IsRightToLeft, value); }

    bool get_IsStyleSetFromGenerator() { return ReadInternalFlag2(InternalFlags2::IsStyleSetFromGenerator); }
    void set_IsStyleSetFromGenerator(bool value) { return WriteInternalFlag2(InternalFlags2::IsStyleSetFromGenerator, value); }

    bool get_IsStyleUpdateInProgress() { return ReadInternalFlag(InternalFlags::IsStyleUpdateInProgress); }
    void set_IsStyleUpdateInProgress(bool value) { return WriteInternalFlag(InternalFlags::IsStyleUpdateInProgress, value); }

    bool get_IsTemplatedParentAnFE() { return ReadInternalFlag2(InternalFlags2::IsTemplatedParentAnFE); }
    void set_IsTemplatedParentAnFE(bool value) { return WriteInternalFlag2(InternalFlags2::IsTemplatedParentAnFE, value); }

    bool get_IsTemplateRoot() { return get_TemplateChildIndex() == 1; }

    bool get_IsThemeStyleUpdateInProgress() { return ReadInternalFlag(InternalFlags::IsThemeStyleUpdateInProgress); }
    void set_IsThemeStyleUpdateInProgress(bool value) { return WriteInternalFlag(InternalFlags::IsThemeStyleUpdateInProgress, value); }

    static KeyboardNavigation* get_KeyboardNavigation();

    TRefCountedPtr<Object> get_LoadedPending() { return GetValue(get_LoadedPendingProperty()); }
    DECLARE_READONLY_DEPENDENCY_PROPERTY(LoadedPending);

    static PopupControlService* get_PopupControlService(); 

    bool get_PotentiallyHasMentees() { return ReadInternalFlag(InternalFlags::PotentiallyHasMentees); }
    void set_PotentiallyHasMentees(bool value) { return WriteInternalFlag(InternalFlags::PotentiallyHasMentees, value); }

    bool get_ShouldLookupImplicitStyles() { return ReadInternalFlag(InternalFlags::ShouldLookupImplicitStyles); }
    void set_ShouldLookupImplicitStyles(bool value) { return WriteInternalFlag(InternalFlags::ShouldLookupImplicitStyles, value); }

    bool get_StoresParentTemplateValues() { return ReadInternalFlag(InternalFlags::StoresParentTemplateValues); }
    void set_StoresParentTemplateValues(bool value) { return WriteInternalFlag(InternalFlags::StoresParentTemplateValues, value); }

    bool get_SubtreeHasLoadedChangeHandler() { return ReadInternalFlag2(InternalFlags2::TreeHasLoadedChangeHandler); }
    void set_SubtreeHasLoadedChangeHandler(bool value) { return WriteInternalFlag2(InternalFlags2::TreeHasLoadedChangeHandler, value); }

    virtual FrameworkTemplate* get_TemplateCache() { return NULL; }
    virtual void set_TemplateCache(FrameworkTemplate* pValue) { }

    virtual UIElement* get_TemplateChild() { return m_pTemplateChild; }
    virtual void set_TemplateChild(UIElement* pValue);

    int get_TemplateChildIndex();
    void set_TemplateChildIndex(int value);

    virtual FrameworkTemplate* get_TemplateInternal() { return NULL; }

    Style* get_ThemeStyle() { return m_pThemeStyleCache; }

    bool get_ThisHasLoadedChangeEventHandler();

    TRefCountedPtr<Object> get_UnloadedPending() { return GetValue(get_UnloadedPendingProperty()); }
    DECLARE_READONLY_DEPENDENCY_PROPERTY(UnloadedPending);

#pragma endregion Internal Properties

#pragma region Internal Events

    void add_InheritedPropertyChanged(InheritedPropertyChangedEventHandler* pValue) { set_PotentiallyHasMentees(true); AddEventHandler(get_InheritedPropertyChangedEvent(), (Delegate*)pValue); }
    void remove_InheritedPropertyChanged(InheritedPropertyChangedEventHandler* pValue) { RemoveEventHandler(get_InheritedPropertyChangedEvent(), (Delegate*)pValue); }
    DECLARE_EVENT(InheritedPropertyChanged);

    void add_ResourcesChanged(EventHandler* pValue) { set_PotentiallyHasMentees(true); AddEventHandler(get_ResourcesChangedEvent(), (Delegate*)pValue); }
    void remove_ResourcesChanged(EventHandler* pValue) { RemoveEventHandler(get_ResourcesChangedEvent(), (Delegate*)pValue); }
    DECLARE_EVENT(ResourcesChanged);

#pragma endregion Internal Events

#pragma region Internal Fields

    TWeakPtr<DependencyObject> m_pTemplatedParent;
    static TRefCountedPtr<NumberSubstitution> DefaultNumberSubstitution;
    static UncommonField<ResourceDictionary> ResourcesField;
    static PropertyInfo* XElement_Name_PropertyInfo;
#pragma endregion Internal Fields

private:

#pragma region Private Methods
    static void StaticConstructor();
    static void CleanupStaticAllocations();

    static void AddStyleHandlersToEventRoute(EventRoute* pRoute, DependencyObject* pSource, TArray<RoutedEventHandlerInfo>* pHandlers);
    void ClearInheritanceContext();
    static TRefCountedPtr<Object> CoerceFlowDirectionProperty(DependencyObject* pDO, Object* pValue);
    static TRefCountedPtr<Object> CoerceFontFamily(DependencyObject* pDO, Object* pValue);
    static TRefCountedPtr<Object> CoerceFontSize(DependencyObject* pDO, Object* pValue);
    static TRefCountedPtr<Object> CoerceFontStyle(DependencyObject* pDO, Object* pValue);
    static TRefCountedPtr<Object> CoerceFontWeight(DependencyObject* pDO, Object* pValue);
    Vector ComputeAlignmentOffset(const Size& clientSize, const Size& inkSize);
    void ConnectLoadedEvents(FrameworkObject* pFOMentor, bool isLoaded);
    void ConnectMentor(DependencyObject* pMentor);
    void DisconnectLoadedEvents(FrameworkObject* pFOMentor, bool isLoaded);
    void DisconnectMentor(DependencyObject* pMentor);
    static FrameworkServices* EnsureFrameworkServices();
    static TRefCountedPtr<Object> FindBestMatchInResourceDictionary(ResourceDictionary* pTable, ArrayList* pKeys, int exactMatch, int* pBestMatch);
    Size FindMaximalAreaLocalSpaceRect(Transform* pLayoutTransform, const Size& transformSpaceBounds);
    static TRefCountedPtr<Object> FindTemplateResourceInTree(DependencyObject* pTarget, ArrayList* pKeys, int exactMatch, int* pBestMatch);
    static TRefCountedPtr<Object> GetActualHeight(DependencyObject* pDO, BaseValueSource::Enum* pSource);
    static TRefCountedPtr<Object> GetActualWidth(DependencyObject* pDO, BaseValueSource::Enum* pSource);
    static FlowDirection::Enum GetFlowDirectionFromVisual(DependencyObject* pVisual);
    TRefCountedPtr<Transform> GetFlowDirectionTransform();
    Object* GetInheritableValue(DependencyProperty* pDP, FrameworkPropertyMetadata* pFMetadata);
    static ResourceDictionary* GetInstanceResourceDictionary(FrameworkElement* pFE, FrameworkContentElement* pFCE);
    Point GetRenderTransformOrigin();
    static ResourceDictionary* GetStyleResourceDictionary(FrameworkElement* pFE, FrameworkContentElement* pFCE);
    static ResourceDictionary* GetTemplateResourceDictionary(FrameworkElement* pFE, FrameworkContentElement* pFCE);
    static ResourceDictionary* GetThemeStyleResourceDictionary(FrameworkElement* pFE, FrameworkContentElement* pFCE);
    bool GetValueFromTemplatedParent(DependencyProperty* pDP, EffectiveValueEntry* pEntry);
    static TRefCountedPtr<String> GetXLinqTagName(Object* pItem, Type* pType);
    static TRefCountedPtr<XmlNamespaceManager> GetXmlNamespaceManager(DependencyObject* pTarget);
    static TRefCountedPtr<String> GetXmlTagName(Object* pItem, DependencyObject* pTarget);
    bool IsLogicalDescendent(DependencyObject* pChild);
    static bool IsMarginValid(Object* pValue);
    static bool IsMaxWidthHeightValid(Object* pValue);
    static bool IsMinWidthHeightValid(Object* pValue);
    static bool IsWidthHeightValid(Object* pValue);
    static void NumberSubstitutionChanged(DependencyObject* pDO, DependencyPropertyChangedEventArgs* e);
    static void OnContextMenuClosingThunk(Object* pSender, ContextMenuEventArgs* e) { ((FrameworkElement*)pSender)->OnContextMenuClosing(e); }
    static void OnContextMenuOpeningThunk(Object* pSender, ContextMenuEventArgs* e) { ((FrameworkElement*)pSender)->OnContextMenuOpening(e); }
    static void OnCursorChanged(DependencyObject* pDO, DependencyPropertyChangedEventArgs* e);
    static void OnDataContextChanged(DependencyObject* pDO, DependencyPropertyChangedEventArgs* e);
    static void OnFlowDirectionChanged(DependencyObject* pDO, DependencyPropertyChangedEventArgs* e);
    static void OnForceCursorChanged(DependencyObject* pDO, DependencyPropertyChangedEventArgs* e);
    static void OnGotKeyboardFocus(Object* pSender, KeyboardFocusChangedEventArgs* e);
    static void OnLayoutTransformChanged(DependencyObject* pDO, DependencyPropertyChangedEventArgs* e);
    static void OnLostKeyboardFocus(Object* pSender, KeyboardFocusChangedEventArgs* e);
    void OnMentorInheritedPropertyChanged(Object* pSender, InheritedPropertyChangedEventArgs* e);
    void OnMentorLoaded(Object* pSender, RoutedEventArgs* e);
    void OnMentorResourcesChanged(Object* pSender, EventArgs* e);
    void OnMentorUnloaded(Object* pSender, RoutedEventArgs* e);
    static void OnPreviewGotKeyboardFocus(Object* pSender, KeyboardFocusChangedEventArgs* e);
    static void OnQueryCursorOverride(Object* pSender, QueryCursorEventArgs* e);
    static void OnStyleChanged(DependencyObject* pDO, DependencyPropertyChangedEventArgs* e);
    static void OnThemeStyleKeyChanged(DependencyObject* pDO, DependencyPropertyChangedEventArgs* e);
    static void OnToolTipClosingThunk(Object* pSender, ToolTipEventArgs* e);
    static void OnToolTipOpeningThunk(Object* pSender, ToolTipEventArgs* e);
    static void OnTransformDirty(DependencyObject* pDO, DependencyPropertyChangedEventArgs* e);
    void PrivateInitialized();
    void RaiseDependencyPropertyChanged(Object* pKey, DependencyPropertyChangedEventArgs* args);
    void RaiseInitialized(Object* pKey, EventArgs* e);
    void SetLayoutOffset(const Vector& offset, const Size& oldRenderSize);
    static bool ShouldUseSystemFont(FrameworkElement* pFE, DependencyProperty* pDP);
    void TryFireInitialized();

#pragma endregion Private Methods

#pragma region Private Properties

    bool get_HasHeightEverChanged() { return ReadInternalFlag(InternalFlags::HasHeightEverChanged); }
    void set_HasHeightEverChanged(bool value) { return WriteInternalFlag(InternalFlags::HasHeightEverChanged, value); }

    bool get_HasWidthEverChanged() { return ReadInternalFlag(InternalFlags::HasWidthEverChanged); }
    void set_HasWidthEverChanged(bool value) { return WriteInternalFlag(InternalFlags::HasWidthEverChanged, value); }

    bool get_NeedsClipBounds() { return ReadInternalFlag(InternalFlags::NeedsClipBounds); }
    void set_NeedsClipBounds(bool value) { return WriteInternalFlag(InternalFlags::NeedsClipBounds, value); }

#pragma endregion Private Properties

#pragma region Private Fields

    static PropertyMetadata* m_pActualHeightMetadata;
    static PropertyMetadata* m_pActualWidthMetadata;
    static TRefCountedPtr<Style> m_pDefaultFocusVisualStyle;
    unsigned int m_flags;
    unsigned int m_flags2;

    // [ThreadStatic]
    static TRefCountedPtr<FrameworkServices> m_pFrameworkServices;

    TRefCountedPtr< ItemStructList<DependencyProperty*> > m_pInheritableProperties;
    TWeakPtr<DependencyObject> m_pParent;
    TRefCountedPtr<Style> m_pStyleCache;
    TRefCountedPtr<UIElement> m_pTemplateChild;
    TRefCountedPtr<Style> m_pThemeStyleCache;

    // WPFG Minor deviation, these are now WeakReferenceObjects, not DOs to prevent cyclical references.
    static UncommonField< Object > InheritanceContextField;
    static UncommonField< Object > MentorField;
    static UncommonField<SizeBox> UnclippedDesiredSizeField;  

#pragma endregion Private Fields
 
};
 

 



}; // namespace AVUI
